package com.lovelyj.trip_by_train.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lovelyj.trip_by_train.common.R;
import com.lovelyj.trip_by_train.entity.User;
import com.lovelyj.trip_by_train.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user) {
        log.info("登录中。。。");
        String username = user.getUsername();
        String password = user.getPassword();
        password= DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        lambdaQueryWrapper.eq(User::getPassword, password);
        user = userService.getOne(lambdaQueryWrapper);
        if (user != null) {
            request.getSession().setAttribute("user",user.getId());
            log.info(user.getId().toString());
            return R.success(user);}
        return R.error("登陆失败");
    }

    @PostMapping("/register")
    public R<String> register(HttpServletRequest request, @RequestBody User user){
        log.info("注册中");
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        if(userService.count(lambdaQueryWrapper)>0){
            return R.error("用户名已被注册，换一个用户名吧");
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userService.save(user);
        return R.success("注册成功");

    }

    @GetMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("登出成功");
    }

}
